<template>
	<div class="app-container flex col-top row-between">
		<div class="bgWhite radius8" style="width: 280px;padding: 20px;">
			<div>
				<span class="main-color">产品类别</span>
				<!-- <span class="fs12 color2 cursor" @click="resetAdd()">新增</span> -->
			</div>
			<div class="mt15">
				<!-- <div class="cursor fs14" style="color: #606266;padding-left: 28px;" @click="queryParams.classifyId = '',getList()">全部</div> -->
				<el-tree :data="data" node-key="id" default-expand-all :expand-on-click-node="false"
					@node-click="handleNodeClick"  :highlight-current="true">
					<template #default="{ node, data }">
						<div class="custom-tree-node flex col-center row-between">
							<span>{{ node.label }}</span>
							<span>
								<el-icon color="#4DACB1" :size="16" @click.stop="() => append(node,data)"
								v-hasPermi="['product:classify:add']"
								>
									<Plus />
								</el-icon>
								<el-icon color="#4DACB1" :size="16"  class="mr10 ml10" v-if="node.data.id != -1" type="text" size="mini" @click.stop="() => edit(node,data)"
								v-hasPermi="['product:classify:add']"
								>
									<Edit />
								</el-icon>
								<el-icon color="#4DACB1" :size="16" v-if="node.data.id != -1" type="text" size="mini" @click.stop="() => remove(node, data)"
								v-hasPermi="['product:classify:remove']"
								>
									<Delete />
								</el-icon>
							</span>
						</div>
					</template>
				</el-tree>
			</div>
		</div>
		<div style="width: calc(100% - 300px);">
			<div class="bgWhite radius8">
				<el-form class="p20 flex col-top row-between" style="padding-bottom: 0;" label-width="80px"
					:model="queryParams" ref="queryForm" :inline="true">
					<div>
						<el-form-item label="关键词" prop="keyword">
							<el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable class="resetInput"
								style="width: 200px" :suffix-icon="Search" @keyup.enter="handleQuery" />
						</el-form-item>
						<el-form-item label="剂型" prop="dosageForm">
							<el-select v-model="queryParams.dosageForm" placeholder="请选择" size="large"
								style="width: 200px">
								<el-option v-for="dict in bus_sosage_form" :key="dict.value" :label="dict.label"
									:value="dict.value" />
							</el-select>
						</el-form-item>
						<el-form-item label="毒性" prop="toxicity">
							<el-select v-model="queryParams.toxicity" placeholder="请选择" size="large"
								style="width: 200px">
								<el-option v-for="dict in bus_toxicity" :key="dict.value" :label="dict.label"
									:value="dict.value" />
							</el-select>
						</el-form-item>
					</div>
					<el-form-item  style="margin-right: 0">
						<div class="flex col-center row-end">
							<el-button class="searchBtn" type="defaultBtn" @click="handleQuery">查询</el-button>
							<el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
						</div>
					</el-form-item>
				</el-form>
			</div>

			<div class="bgWhite radius8 p20 mt25">
				<div class="flex col-center row-between mb20">
					<span class="fb fs16">产品列表</span>
					<div>
						<el-button type="defaultBtn" @click="handleAdd()"
							v-hasPermi="['product:add']">新增产品</el-button>
						<el-button type="operate" @click="importProduct()"
							v-hasPermi="['product:export']"
						>导入</el-button>
					</div>
				</div>

				<el-table v-loading="loading" :data="productList" style="width: 100%;" :header-row-style="{
					background: '#FAFAFA',
					color: '#0C1019',
					height: '54px',
				  }" :cell-style="{ height: '54px' }" @selection-change="handleSelectionChange">
					<!-- <el-table-column type="selection" width="55" align="center" /> -->
					<el-table-column label="主键" align="center" prop="id" v-if="false" />

					<el-table-column label="产品图片" align="center" prop="productPromoImageUrl" width="120">
						<template #default="scope">
							<img :src="scope.row.productPromoImageUrl ? scope.row.productPromoImageUrl : defaultImg" 
							class="radius8" style="width: 80px; height: 80px" />
						</template>
					</el-table-column>
					<el-table-column label="产品名称" align="center" prop="productName">
						<template #default="scope">
							<span class="main-color">{{scope.row.productName}}</span>
						</template>
					</el-table-column>
					<el-table-column label="农药登记证号" align="center" prop="pesticideRegistrationNumber" width="150" />
					<el-table-column label="品牌名称" align="center" prop="brandName" />
					<el-table-column label="产品类别" align="center" prop="productCategory">
						<template #default="scope">
								<dict-tag :options="bus_product_category" :value="scope.row.productCategory" />
						</template>
					</el-table-column>
					<el-table-column label="剂型" align="center" prop="dosageForm">
						<template v-slot="scope">
							<dict-tag :options="bus_sosage_form" :value="scope.row.dosageForm" />
						</template>
					</el-table-column>

					<el-table-column label="毒性" align="center" prop="toxicity">
						<template v-slot="scope">
							<dict-tag :options="bus_toxicity" :value="scope.row.toxicity" />
						</template>
					</el-table-column>
					<el-table-column label="有效成分1" align="center" prop="activeIngredient1" width="150" />
					<el-table-column label="有效成分2" align="center" prop="activeIngredient2" width="150" />
					<el-table-column label="有效成分3" align="center" prop="activeIngredient3" width="150" />

					<el-table-column label="启用状态" align="center" prop="status">
						<template v-slot="scope">
							<el-switch v-model="scope.row.status" class="ml-2" inline-prompt active-text="启用"
								inactive-text="禁用" @click="updateEnabled(scope.row)" :loading="loading" />
						</template>
					</el-table-column>
					<el-table-column label="更新时间" align="center" prop="updateTime" width="200" />

					<el-table-column fixed="right" label="操作" align="center" width="200">
						<template v-slot="scope">
							<el-button size="mini" type="text" @click="handleDetail(scope.row)"
							v-hasPermi="['product:detail']"
							>查看详情</el-button>							
							<el-button size="mini" type="text" @click="handleUpdate(scope.row)"
								v-hasPermi="['product:edit']">编辑</el-button>
							<el-button size="mini" type="text" @click="handleDelete(scope.row)"
								v-hasPermi="['product:remove']">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
					v-model:limit="queryParams.pageSize" @pagination="getList" />
			</div>
		</div>
		<!-- 编辑/新增分类树弹窗 -->
		<el-dialog :title="title" center v-model="treeFormOpen" width="385px" append-to-body>
		  <el-form ref="refTreeForm" :model="form" :rules="rules" label-width="80px">
		    <el-form-item label="名称:" prop="name">
		      <el-input
		          size="large"
		          v-model="form.name"
		          placeholder="请输入"
				  style="200px"
		      />
		    </el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer text-right mt30">
			  <el-button class="cancelSubBtn" @click="treeFormOpen = false">取 消</el-button>
			  <el-button type="primary" @click="treeDataSubmit" class="mainSubBtn">确 定</el-button>
		  </div>
		</el-dialog>
		<!-- 批量导入产品 -->
		<el-dialog title="批量导入" center v-model="upload.open" width="694px" append-to-body>
		   <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
		      :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
		      :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<div>
					<div class="flex col-top">
						<img src="@/assets/images/Img.png" width="80" height="80" alt="" />
						<div class="text-left ml15 mt5" style="text-align: left;">
							<span class="fb color333 mr5 mt5">上传导入产品文件</span>
							<el-link type="primary" :underline="false" 
							style="font-size:12px;vertical-align: baseline;border: 1px solid #4DACB1;background: #EDF6F7;border-radius: 2px;line-height: 22px;padding: 0 4px;"
							   @click.stop="importTemplate">下载模板</el-link>
							<div class="fs12 mt6 mb8">
								 <span>文件后缀名必须为xls 或xlsx（即Excel格式），文件大小不得大于10M，最多支持导入3000条数据</span>
							</div> 
							 <div class="main-color fs12">上传文件</div>
						</div>
					</div>
				</div>
		   </el-upload>
		   <template #footer>
		      <div class="dialog-footer text-right">
				   <el-button class="cancelSubBtn" @click="upload.open = false">取 消</el-button>
				   <el-button type="primary" @click="submitFileForm" class="mainSubBtn">确 定</el-button>
		      </div>
		   </template>
		</el-dialog>
		<!-- //新增产品 -->
		<operateProduct ref="productPop" @refreshList="getList"></operateProduct>
	</div>
</template>


<script>
	import {
		Search
	} from '@element-plus/icons-vue'
	import {
		listClassify, //商品分类树
		addTree,//商品分类树新增
		delTree,//商品分类树删除
		listProduct, //产品列表
		delProduct,//删除产品
		updateProduct
	} from "@/api/business/product";
	import { getToken } from "@/utils/auth";
	import operateProduct from "./components/operateProduct.vue"
	export default {
		components:{
			operateProduct
		},
		data() {
			const data = []
			return {
				bus_toxicity:this.useDict('bus_toxicity').bus_toxicity,
				bus_sosage_form:this.useDict('bus_sosage_form').bus_sosage_form,
				bus_product_category:this.useDict('bus_product_category').bus_product_category,
				bus_active_ingredient_content:this.useDict('bus_active_ingredient_content').bus_active_ingredient_content,
				loading: true, // 遮罩层
				ids: [], // 选中数组
				single: true, // 非单个禁用
				multiple: true, // 非多个禁用
				showSearch: true, //显示搜索条件
				total: 0, // 总条数
				productList: [], // 产品表格数据
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					classifyId:'',//分类id
					keyword: null, // 产品名称 品牌名称 产品编码
					toxicity: null, // 毒性
					dosageForm: null, // 剂型
				}, //查询参数
				data: JSON.parse(JSON.stringify(data)),
				data: JSON.parse(JSON.stringify(data)),
				title: '新增', // 弹出层标题
				treeFormOpen:false,//新增弹窗
				rules: {
				  name: [{required: true, message: "请输入类别名称", trigger: "blur"}],
				},
				form:{
					name:'',
					parentId:'',//父id
					ancestors:'',//id链
					level:'',//层级
					id:''
				},
				upload:{
				   // 是否显示弹出层（用户导入）
				   open: false,
				   // 弹出层标题（用户导入）
				   title: "",
				   // 是否禁用上传
				   isUploading: false,
				   // 是否更新已经存在的用户数据
				   updateSupport: 0,
				   // 设置上传的请求头部
				   headers: { Authorization: "Bearer " + getToken() },
				   // 上传的地址
				   url: import.meta.env.VITE_APP_BASE_API+'/product/importData'
				},
			}
		},
		created() {
			this.getTree(1)
		},
		methods: {
			/** 下载模板操作 */
			importTemplate() {
			   this.download("/product/templateDownload", {
			   }, `product_template${new Date().getTime()}.xlsx`);
			},
			//导入
			importProduct(){
				this.upload.open = true	
			},
			/**文件上传中处理 */
			handleFileUploadProgress(event, file, fileList) {
			   this.upload.isUploading = true;
			},
			/** 文件上传成功处理 */
			handleFileSuccess(response, file, fileList){
			   this.upload.open = false;
			   this.upload.isUploading = false;
			   this.$refs["uploadRef"].handleRemove(file);
			   this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
			   this.getList();
			},
			submitFileForm() {
			   this.$refs["uploadRef"].submit();
			},
			handleNodeClick(e){
				if(e.id*1 != -1){
					this.queryParams.classifyId = e.id	
			    }else{
					this.queryParams.classifyId = ''
				}				
				this.getList();
			},
			resetAdd(){
				this.reset()
				this.treeFormOpen = true
			},
			reset(){
				this.form = {
					name:'',
					parentId:'',//父id
					ancestors:'',//id链
					level:'',//层级
					id:''
				}
			},
			append(node,data) {
				console.log(node,'level')
				this.reset()
				this.treeFormOpen = true
				if(node.data.id*1 != -1){
					this.form.parentId = node.data.id
				}
				this.form.ancestors = node.data.ancestors
				this.form.level = node.level
			},
			// 编辑
			edit(node,data){
				this.title = '编辑'
				this.reset()
				this.treeFormOpen = true
				this.form.parentId = node.data.parentId
				this.form.ancestors = node.data.ancestors
				this.form.name = node.data.name
				this.form.id = node.data.id
				this.form.level = node.level
			},
			remove(node, data) {
				console.log(node,'node')
				let that = this
				this.$modal
				  .confirm('是否确认删除"' + node.data.label + '"的数据项？')
				  .then(function () {
				    delTree(node.data.id).then(res=>{
						if(res.code == 200){
							that.getTree()
							this.$modal.msgSuccess("删除成功");
						}
					})
				  })
				  .catch(() => { });
				
			},
			//分类树
			getTree(num) {
				listClassify().then(res => {
					if (res.code == 200) {
						let arr = [{
							ancestors:'',
							id:'-1',
							name:'全部',
							parentId:''
						}]
						let dataArr = arr.concat(res.data)
						for (let key in dataArr) {
							dataArr[key].label = dataArr[key].name
						}
						this.data = this.handleTree(dataArr)
						console.log(dataArr,'this.data1')
						console.log(this.data,'this.data')
						if(num == 1){
							this.getList()
						}
					}
				})
			},
			// 分类树新增
			treeDataSubmit(){
				console.log(this.form,'form')
				addTree(this.form).then(res=>{
					if(res.code == 200){
						this.treeFormOpen = false
						this.getTree()
					}
				})
			},
			//查询产品列表
			getList() {
				this.loading = true;
				listProduct(this.queryParams).then((response) => {
					this.productList = response.rows;
					for(let key in this.productList){
						this.productList[key].status = this.productList[key].status == '0' ? true : false
					}
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 启用状态操作
			updateEnabled(row) {
				this.loading = true;
				let item = {
					id: row.id,
					status: row.status == true ? 0 : 1,
				}
				updateProduct(item).then((response) => {
					this.$modal.msgSuccess("更新成功");
					this.loading = false;
					this.getList();
				});
			},
			//新增
			handleAdd() {
				this.$refs.productPop.open('')
				// this.$router.push('/product/operate')
			},
			// 编辑
			handleUpdate(row) {
				this.$refs.productPop.open(row.id)
				// this.$router.push('/product/operate?id=' + row.id)
			},
			// 查看详情
			handleDetail(row){
				this.$refs.productPop.open(row.id,1)
				// this.$router.push('/product/productDetail?id=' + row.id)
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id);
				this.single = selection.length !== 1;
				this.multiple = !selection.length;
			},
			handleDelete(row) {
				const ids = row.id || this.ids;
				let that = this
				this.$modal
					.confirm('是否确认删除产品编号为"' + ids + '"的数据项？')
					.then(function() {
						delProduct(ids).then(res => {
							that.getList()
							this.$modal.msgSuccess("删除成功");
						})
					})
					.catch(() => {});
			}
		}
	}
</script>
<style>
	.custom-tree-node{
		flex: 1;
	}
	.el-tree-node{
		margin: 6px 0;
	}
</style>